package com.ebelter.btcomlib.models.bluetooth.products.bracelet;


import android.os.Message;
import android.util.Log;
import com.ebelter.btcomlib.models.beans.ScaleUser;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.BraDb;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.BraDb_Table;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.RateBean;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.bean.WalkBean;
import com.ebelter.btcomlib.models.bluetooth.products.bracelet.interfaces.BraceletMesureResult;
import com.ebelter.btcomlib.utils.BaseHandle;
import com.ebelter.btcomlib.utils.BytesUtils;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.raizlabs.android.dbflow.sql.language.Select;


public class BraceletBytesAnalysis extends BaseHandle {

    private static final String TAG = "BraceletBytesAnalysis";
    private BraceletMesureResult braceletMesureResult;

    private BraceletManager.IShHHis mIShHHis;

    ScaleUser mScaleUser;

    public void setmIShHHis(BraceletManager.IShHHis mIShHHis) {
        this.mIShHHis = mIShHHis;
    }

    public BraceletBytesAnalysis(Object... objects) {
        super(objects);
        mScaleUser = ScaleUser.getUser();
    }


    private static final int what_sysTimeSuccess = 0;
    private static final int what_setUserInfoSuccess = 1;
    private static final int what_setXlCyc = 2;
    private static final int what_getRealTime = 3;
    private static final int what_getXlRealTime = 4;

    private static final int what_open_ota_success = 5;
    private static final int what_Low_power = 6;
    private static final int what_version = 7;

    @Override
    public void handleMsg(Message msg) {


        if (braceletMesureResult != null) {
            switch (msg.what) {

                case what_sysTimeSuccess:
                    braceletMesureResult.sysTimeSuccess();
                    break;
                case what_setUserInfoSuccess:
                    braceletMesureResult.setUserInfoSuccess();
                    break;
                case what_setXlCyc:
                    braceletMesureResult.setXlCycSuccess();
                    break;
                case what_getRealTime:
                    braceletMesureResult.getRealTimeData((WalkBean) msg.obj);
                    break;
                case what_getXlRealTime:
                    braceletMesureResult.getRealTimeXlData((RateBean) msg.obj);
                    break;
                case what_open_ota_success:
                    braceletMesureResult.openOtaSuccess();
                    break;
                case what_Low_power:
                    braceletMesureResult.lowpower();
                    break;
                case what_version:
                    braceletMesureResult.version((String) msg.obj);
                    break;

            }
        }


    }

    public byte[] bytes = new byte[0];

    public void resultAnalysis(final byte[] data) {
        LogUtils.i(TAG, "-----data[]------" + BytesUtils.bytes2HexStr(data));
        if (data == null || data.length == 0 || braceletMesureResult == null) {
            return;
        }

        if (data.length > 2) {


            if (data[0] == 0x01 && data[1] == 0x01) {
                int i = data[2];
              //  Toast.makeText(mContext, i == 0 ? "进入OTA成功" : "电量过低", Toast.LENGTH_SHORT).show();

                if (i==0){
                    sendEmptyMessage(what_open_ota_success);
                }else {
                    sendEmptyMessage(what_Low_power);
                }

                return;

            }



            //设置时间成功
            if (data[0] == 0x03 && data[1] == 0x01) {
                LogUtils.i(TAG, "-----data[]------设置时间成功");
                sendEmptyMessage(what_sysTimeSuccess);
                return;
            }
            //设置用户信息成功
            if (data[0] == 0x03 && data[1] == 0x10) {
                LogUtils.i(TAG, "-----data[]------设置用户信息成功");
                sendEmptyMessage(what_setUserInfoSuccess);
                return;
            }
            //设置心率周期成功
            if (data[0] == 0x03 && data[1] == 0x26) {
                LogUtils.i(TAG, "-----data[]------设置心率周期成功");
                sendEmptyMessage(what_setXlCyc);
                return;
            }

            //实时数据0x07
            if (data[0] == 0x02 && data[1] == 0x07) {
                LogUtils.i(TAG, "-----data[]------实时数据0x07");
                realTimeData(data);
                return;
            }

            //实时心率数据0x09
            if (data[0] == 0x02 && data[1] == 0x09) {
                LogUtils.i(TAG, "-----data[]------实时心率数据0x09");
                realTimeXlData(data);
                return;
            }

            //固件版本号
            if (data[0] == 0x02 && data[1] == 0x01) {
                //固件版本号---[02 01 42 59 5F 30 32 5F 48 32 39 30 32 5F 30 38 31 36 00 00]
                LogUtils.i(TAG, "-----data[]------固件版本号---"+BytesUtils.bytes2HexStr(data));
                //解析出来的固件版本号:BY_02_H2902_0816����
                byte[] bytes = new byte[16];
                System.arraycopy(data,2,bytes,0,16);
                String version = new String(bytes);
                LogUtils.i(TAG,"解析出来的固件版本号:"+ version);//BY_02_H2902_0816
                LogUtils.i(TAG,"address:"+ address);
                sendMessageObj(what_version, version);
                return;
            }

        }


        post(new Runnable() {
            @Override
            public void run() {
                if (data[0] == 0x02 && data[1] == 0x08) {
                    bytes = new byte[0];
                }

                bytes = HexUtil.arraycat(bytes, data);
                LogUtils.i(TAG, "-----bytes[]------" + BytesUtils.bytes2HexStr(bytes));

                if (bytes.length > 2 && bytes[0] == 0x02 && bytes[1] == 0x08) {
                    if (!subPackageOnce(bytes)) {
                        //历史数据
                        if (bytes[0] == 0x02 && bytes[1] == 0x08) {  //历史数据
                            try {
                                String time = saveData(bytes);
                                bytes = new byte[0];
                                LogUtils.i(TAG, "-----data[]------历史数据--time = " + time);
                                if (mIShHHis != null) mIShHHis.sysTimeFinish(time);
                            } catch (Exception e) {
                                e.printStackTrace();
                                LogUtils.i(TAG, "-------------------保存数据出错");
                                if (mIShHHis != null) mIShHHis.sysTimeDataError();
                            }
                        }
                    }
                } else {
                    bytes = new byte[0];
                }


            }
        });


    }

    //获取实时心率数据接口
    private void realTimeXlData(byte[] data) {

        RateBean rateBean = new RateBean(System.currentTimeMillis(), 0);
        if (data[2] == 0x01) {
            // if (braceletManager!=null)braceletManager.isOpenRealTimeRate=true;
            if (data[3] == 0x00) {
                rateBean.station = 0;
            } else {
                rateBean.station = 1;
                rateBean.rate = data[3];
            }
        } else {
            rateBean.station = 2;
            //  if (braceletManager!=null)braceletManager.isOpenRealTimeRate=false;
        }
        sendMessageObj(what_getXlRealTime, rateBean);

    }

    //获取实时数据接口
    private void realTimeData(byte[] data) {

        String s = HexUtil.bytesToHexString(data);
        String s1 = s.substring(4, 6);
        String s2 = s.substring(6, 8);
        String s3 = s.substring(8, 10);
        String sum;
        if (s3.equals("00")) {
            sum = s2 + s1;
        } else {
            sum = s3 + s2 + s1;
        }
        int step = HexUtil.hexStringToAlgorism(sum);

        String s4 = s.substring(16, 18);
        String s5 = s.substring(18, 20);
        String s6 = s.substring(20, 22);
        String sum2;
        if (s6.equals("00")) {
            sum2 = s5 + s4;
        } else {
            sum2 = s6 + s5 + s4;
        }
        int dis = HexUtil.hexStringToAlgorism(sum2);

        String s7 = s.substring(22, 24);
        String s8 = s.substring(24, 26);
        String s9 = s.substring(26, 28);
        String sum3;
        if (s9.equals("00")) {
            sum3 = s8 + s7;
        } else {
            sum3 = s9 + s8 + s7;
        }
        int cal = HexUtil.hexStringToAlgorism(sum3);
        //LogUtils.e(new RealTimeData(step, data[5], data[6], dis, cal).toString());


        WalkBean walkBean = new WalkBean();
        walkBean.setTimeLong(System.currentTimeMillis());
        walkBean.steps = step;
        walkBean.distance = dis;
        walkBean.calories = cal;

        sendMessageObj(what_getRealTime, walkBean);


    }


    public boolean subPackageOnce(byte[] mbyte) {

        if (mbyte[0] == 0x02 && mbyte[1] == 0x08) {
            int len = mbyte[7] == 0x2A ? 50 : 68; //两套协议历史数据长度不一样
            if (mbyte.length == len) {
                return false;
            } else if (mbyte.length > len) {
                bytes = new byte[0];
            }
            return true;
        } else {
            return false;

        }
    }

    public static final String[] time = {"00", "10", "20", "30", "40", "50"};

    private String saveData(byte[] data) {

        Log.i(TAG, "------保存数据：" + HexUtil.bytesToHexString(data));

//        0208
//        12 09 0c 13（12日19时）
//        48
//        3c
//        01 a50000 0000004e 0000  ---65步 0 0 0 78
//        01 000000 00000051 0000  --- 0步 0 0 0 81
//        01 310400 00000051 0000 ---1073步 0 0 0 81
//        01 2d0400 00000050 0000  ---1069步 0 0 0 80
//        01 2b0400 00000050 0000  ---1067步 0 0 0 80
//        01 fc0300  0000004b 0000  ----1020步 0 0 0  75

        int year = data[2];
        int month = data[3];
        int day = data[4];
        int hour = data[5];


        if (hour < 0) {// 表示当天无有效数据
            //月日时
            String retureTime2 = "#" + year + (month < 10 ? "0" + month : month) + (day < 10 ? "0" + day : day) + "00";
            return retureTime2;//
        }

        //年月日时
        String date = "" + year + (month < 10 ? "0" + month : month) + (day < 10 ? "0" + day : day) + (hour < 10 ? "0" + hour : hour);
        //月日时
        String retureTime = "" + (month < 10 ? "0" + month : month) + (day < 10 ? "0" + day : day) + (hour < 10 ? "0" + hour : hour);


        for (int i = 0; i < 6; i++) {
            int type = data[i * 10 + 1 + 7];

            byte[] d = {data[i * 10 + 11], data[i * 10 + 10], data[i * 10 + 9]};

            String s = BytesUtils.bytes2HexStr2(d);
            int step = NumUtils.hexStr2dec(s);

            int heart0 = data[i * 10 + 12];
            int heart1 = data[i * 10 + 13];
            int heart2 = data[i * 10 + 14];
            int heart3 = data[i * 10 + 15];


            String time2 = date + time[(i) % 6];

            LogUtils.i(TAG, "-时间=" + time2 + "--步数=" + step + "--type=" + type + "--heart0=" + heart0 + "--heart1=" + heart1 + "--heart2=" + heart2 + "--heart3=" + heart3);

            long time3 = NumUtils.string2Long(time2);//解析到的当前时间
            //0x01 为记步数据 0x10 为睡眠数据（0x11 为开始睡眠 0x12 为清醒状态 0x13 为浅睡状态 0x14 为深睡状态 0x15 为结束睡眠）
            BraDb br = new Select().from(BraDb.class).where(BraDb_Table.timeStr.eq(time3)).querySingle();//查询当前时间是否有此时间的记录数据了
            if (br == null) {
                LogUtils.i(TAG, "说明数据库里面还没这个数据--" + time2 + "--插入数据");
                BraDb braDb = new BraDb();
                braDb.timeStr = time3;
                braDb.dateType = type;
                braDb.step = step;
                braDb.heart = heart0;
                braDb.heart1 = heart1;
                braDb.heart2 = heart2;
                braDb.heart3 = heart3;
                braDb.save();
            } else {
                LogUtils.i(TAG, "说明数据库里面有这个数据--" + time2 + "--更新数据");
                br.timeStr = time3;
                br.step = step;
                br.dateType = type;
                br.heart = heart0;
                br.heart1 = heart1;
                br.heart2 = heart2;
                br.heart3 = heart3;
                br.update();
            }

        }

        return retureTime;
    }

    public void setBraceletMeasureCallback(BraceletMesureResult braceletMesureResult) {
        this.braceletMesureResult = braceletMesureResult;
    }

    private BraceletManager braceletManager;

    public void setBraceletManager(BraceletManager braceletManager) {
        this.braceletManager = braceletManager;
    }

    private String address;
    public void connectAddress(String address){
        this.address = address;
    }
}
